<?php

// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\admin\model\ThemeModel;
use cmf\controller\AdminBaseController;
use think\Db;
use cmf\lib\Upload;
use think\facade\View;

class SaveTableController extends AdminBaseController {

    public function doSaveTable(){
        $request_data = $this->request->param();
        
        $record = array();
        
        $request_count = $fail_count = count($request_data['image']);
        $success_count = 0;
        if($this->request->isPost() && !empty($request_data['uploadType'])){
            switch ($request_data['uploadType']){
                case '1': //文件夹
                    $data = $this->_dealClassData($request_data);
                    break;
                case '2'://图片
                    $data = $this->_dealProductData($request_data);
                    break;
            }
            
            if(!empty($data)){                
                foreach ($data as $value){
                    Db::startTrans();
                    $middle_data = array(
                        'post_title'=>strstr($value['name'],'.',true),
                        'more'=> json_encode(array(
                            'thumbnail'=>$value['path']
                        )),
                        'create_time'=>time(),
                        'update_time'=>time(),
                        'published_time'=>time(),
                        'user_id'=>1
                    );
                    $post_table = $value['table_pre'] .'_post';
                    $relation_table = $value['table_pre'] .'_category_post';
                    $insertId = Db::name($post_table)->insertGetId($middle_data);
                    $relation_flag = Db::name($relation_table)->insertGetId(array(
                        'post_id'=>$insertId,
                        'category_id'=>$value['class_id'],
                    ));
                    $middle_data = array();
                    $middle_data['table'] = array(
                        $post_table => $insertId,
                        $relation_table=>$relation_flag
                    ); 
                    if(empty($relation_flag) || empty($insertId)){  
                        
                        $middle_data['status'] = 'Fail(入库)';                        
                        Db::rollback();
                    }else {               
                        $middle_data['status'] = 'Success(入库)';
                        $success_count = $success_count + 1;
                        $fail_count = $fail_count - 1;          
                        Db::commit();
                    }
                    $middle_data['name']= $value['request_name'];
                    
                    $record[] = $middle_data;   
                    
                }
            }
        }
        
        $this->recordFail($record,$request_data['token']);
        return json(array(
            'info'=> sprintf("记录数共计%s个,成功%s个,失败%s个", $request_count,$success_count,$fail_count),
            'code'=>1
        ));
    }
    
    
    
    public function recordFail($request_data,$filename){
        if(empty($request_data)) return false;
        $str = '时间:' . date('Y-m-d H:i:s') . "\r\n";
        foreach ($request_data as $key=> $value){
            $str .= ($key +1) .'.  名称:' . $value['name'] .";  状态:".$value['status']  ."\r\n";
            $str .= '表名' ."\t\t" . '主键' ."\r\n";
            foreach ($value['table'] as $k=>$v){
                $str .=$k ."\t\t" .$v ."\r\n";
            }
           $str .= "\r\n";
        }
        $dir = APP_PATH .'upload/data/log/'.date('Ymd') .'/';
        if(!is_dir($dir)){
            @mkdir($dir, 0777,TRUE);
        }
        
        $file_path = $dir.$filename.'.log';
        
        $handle = fopen($file_path, 'a');
        fwrite($handle, $str);
        fclose($handle);
        
    }






    public function _dealProductData($request_data){
        $data = array();
        if(empty($request_data['image'])) return false;
        else{
            switch ($request_data['product_type']){
                case '1':
                    $table_pre = 'product';
                    break;
                case '2':
                    $table_pre = 'case';
                    break;
                case '3':
                    $table_pre = 'portal';
                    break;                    
            }           
            foreach ($request_data['image'] as $value){
                
                $post_data = array(
                    'class_id'=>$request_data['class_id'],
                    'name'=>$value['name'],
                    'request_name'=>$value['name'],
                    'path'=>$value['path'],
                    'table_pre'=>$table_pre,
                );
                $data[] = $post_data;
            }
        }
        return $data;
    }




    public function _dealClassData($request_data){
        $data = array();
        if(empty($request_data['image'])) return false;
        else{
            foreach ($request_data['image'] as $key=>$value){
                
                
                $name_info = explode('/', $value['name']);
                $count = count($name_info);
                if($count < 3)                    continue;
                $type_name = $name_info[$count-3];
                $class_name = $name_info[$count-2];
                $product_name = $name_info[$count-1];                
                switch ($type_name){
                    case '产品':
                        $table_pre = 'product';
                        break;
                    case '案例':
                        $table_pre = 'case';
                        break;
                    case '新闻':
                        $table_pre = 'portal';
                        break;
                }
                $category_table = $table_pre .'_category'; 
                $class_id = Db::name($category_table)->where('name',$class_name)->value('id');
                if(empty($class_id)){
                    $class_id = Db::name($category_table)->insertGetId(array(
                        'name'=>$class_name,
                    ));
                }
                
                if(empty($class_id))                    continue;
                
                $post_data = array(
                    'class_id'=>$class_id,
                    'name'=>$product_name,
                    'request_name'=>$value['name'],
                    'path'=>$value['path'],
                    'table_pre'=>$table_pre,
                );
                $data[] = $post_data;
                
            }
        }
        
        return $data;
        
    }
    
    
    public function  afterDoSaveTableAction(){
        $table_list = array('product_post','case_post');
        foreach ($table_list as $value){
            
        }
    }
    
    public function getClassByRequestType(){
        $flag = FALSE;
        $message = '参数错误!';
        $request_data = $this->request->param();
        $data = array();
        if($this->request->isPost() && !empty($request_data['product_type'])){
            switch ($request_data['product_type']){
                case '1'://产品
                    $table_pre = 'product';
                    break;
                case '2': //案例
                    $table_pre = 'case';
                    break;
                case '3': //新闻
                    $table_pre = 'portal';
                    break;
            }
                        
            
            
            $data_ = Db::name($table_pre.'_category')
                    ->field('id,name,parent_id')
                    ->where(array(
                        'delete_time'=>0,
                        'status'=>1
                    ))
                    ->select()->toArray();
            $tree       = new Tree();
            $tree->init($data_);
            
      
            $data = $tree->getTreeArray(0); 
            $flag = true;
            $message = '返回成功!';
        }
        
        return json(array(
            'status' => $flag ? 2000 : 4000,
            'data'=>array(
                'class_list'=> array_values($data)
            ),
            'message'=>$message
        
        ));
    }

}
